package com.nulldev.util.security.encryptAPI_rw.impls.serpent;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import com.nulldev.util.VariableAPI.MathUtil;
import com.nulldev.util.data.Variables;
import com.nulldev.util.security.encryptAPI_rw.api.ICipherType;
import com.nulldev.util.security.encryptAPI_rw.api.IStandardBlockingCipher;
import com.nulldev.util.security.encryptAPI_rw.api.IStandardStreamingCipher;

public class SerpentCipher implements IStandardBlockingCipher, IStandardStreamingCipher {

	private static final String[] CIPHER_NAMES =
		{ "Serpent", "SERPENT" };

	@Override
	public String getEncryptorID() {
		return "ecr_v3.internal.serpent";
	}

	@Override
	public String[] getCipherNames() {
		return CIPHER_NAMES;
	}

	@Override
	public long encrypt(final InputStream is, final OutputStream os, final byte[] privateKey) {
		Variables.requireNonNull(is, "is");
		Variables.requireNonNull(os, "os");
		Variables.requireNonNull(privateKey, "privateKey");
		long count = 0;
		final Serpent s = new Serpent();
		s.setKey(Variables.requireNonNullObject(privateKey, "privateKey"));
		final byte[] b = new byte[16];
		try {
			while ((count += (is.read(b, 0, 16))) != -1) {
				s.encrypt(b);
				os.write(b, 0, 16);
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return count;
	}

	@Override
	public long decrypt(final InputStream is, final OutputStream os, final byte[] privateKey) {
		Variables.requireNonNull(is, "is");
		Variables.requireNonNull(os, "os");
		Variables.requireNonNull(privateKey, "privateKey");
		long count = 0;
		final Serpent s = new Serpent();
		s.setKey(Variables.requireNonNullObject(privateKey, "privateKey"));
		final byte[] b = new byte[16];
		try {
			while ((count += (is.read(b, 0, 16))) != -1) {
				s.decrypt(b);
				os.write(b, 0, 16);
			}
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
		return count;
	}

	@Override
	public byte[] encrypt(final byte[] data, final byte[] key) {
		final Serpent s = new Serpent();
		s.setKey(Variables.requireNonNullObject(key, "key"));
		final byte[] out = new byte[MathUtil.padToInterval(Variables.requireNonNullObject(data, "data").length, 16)];
		for (int i = 0; i < data.length; i += 16) {
			final byte[] buf = Arrays.copyOfRange(data, i, i + 16);
			s.encrypt(buf);
			System.arraycopy(buf, 0, out, i, 16);
		}
		return out;
	}

	@Override
	public byte[] decrypt(final byte[] data, final byte[] key) {
		final Serpent s = new Serpent();
		s.setKey(Variables.requireNonNullObject(key, "key"));
		final byte[] out = new byte[MathUtil.padToInterval(Variables.requireNonNullObject(data, "data").length, 16)];
		for (int i = 0; i < data.length; i += 16) {
			final byte[] buf = Arrays.copyOfRange(data, i, i + 16);
			s.decrypt(buf);
			System.arraycopy(buf, 0, out, i, 16);
		}
		return out;
	}

	@Override
	public ICipherType getCipherType() {
		return ICipherType.PRIVATE_KEY;
	}

}
